package com.example.databasepj.service;

import com.example.databasepj.Request.AdminAddMerchantRequest;
import com.example.databasepj.Request.AdminAddUserRequest;
import com.example.databasepj.Request.MerchantUpdateRequest;
import com.example.databasepj.dto.AdminMerchantData;
import com.example.databasepj.dto.AdminUserData;
import com.example.databasepj.dtoAdvanced.*;
import com.example.databasepj.entity.MerchantEntity;
import com.example.databasepj.entity.UserEntity;
import com.example.databasepj.mapper.MerchantMapper;
import com.example.databasepj.mapper.MerchantReviewMapper;
import com.example.databasepj.mapper.OrderMapper;
import com.example.databasepj.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MerchantReviewMapper merchantReviewMapper;

    //获取所有用户列表
    public List<AdminUserData> getAllUsers(){
        List<UserEntity> userEntities= userMapper.getAll();
        List<AdminUserData> results = new ArrayList<>();
        for(int i=0;i<userEntities.size();i++){
            UserEntity userEntity=userEntities.get(i);
            AdminUserData userData = new AdminUserData(userEntity.getUser_id(),userEntity.getUser_name(),userEntity.getStudentOrWorkNumber());
            if(userEntity.getRole()==0){
                userData.setRole("学生");
            }
            else {
                userData.setRole("教职工");
            }
            results.add(userData);

        }
        return results;
    }
    //获取所有商户列表
    public List<AdminMerchantData> getAllMerchants(){
        List<MerchantEntity> merchantEntities=merchantMapper.getAll();
        List<AdminMerchantData> results = new ArrayList<>();
        for(int i=0;i<merchantEntities.size();i++){
            MerchantEntity merchantEntity=merchantEntities.get(i);
            AdminMerchantData merchantData=new AdminMerchantData(merchantEntity.getMerchant_name(),merchantEntity.getMerchant_id(),merchantEntity.getAddress(),merchantEntity.getPassword());
            results.add(merchantData);
        }
        return results;
    }

    public void deleteUser(int userID){
        userMapper.deleteUserByUserId(userID);
    }
    public void deleteMerchant(int merchantID){
        merchantMapper.deleteByMerchant_id(merchantID);
    }

    public void insertMerchant(AdminAddMerchantRequest request){
        if(request.getMerchant_name().equals("") || request.getAddress().equals("") || request.getPassword().equals("")){
            if(request.getMerchant_name().equals("")) request.setMerchant_name(null);
            if(request.getAddress().equals("")) request.setAddress(null);
            if(request.getPassword().equals("")) request.setPassword(null);
        }
        MerchantEntity merchantEntity=new MerchantEntity(request.getMerchant_name(), request.getAddress(), request.getPassword());
        merchantMapper.insertMerchant(merchantEntity);
    }
    public void insertUser(AdminAddUserRequest request){
        UserEntity userEntity=new UserEntity(request.getUser_name(),request.getGender(), request.getStudentOrWorkNumber(), request.getAge(), request.getRole(), request.getPassword());
        userMapper.insertUser(userEntity);
    }
    public void updateMerchant(int merchantID, MerchantUpdateRequest request){
        MerchantEntity merchantEntity = new MerchantEntity(merchantID,request.getMerchant_name(), request.getAddress(), request.getPassword());
        merchantMapper.updateMerchant(merchantEntity);
    }

    public List<UserActivityResponse> userActivity(UserActivityRequest request){
        //现根据类型使用不同的方法
        String type= request.getType();
        int year=Integer.valueOf(request.getQuery_year());
        List<UserActivityResponse> results=new ArrayList<>();
        if(type.equals("weekly")){
            List<OrderCountWeekly> orderCountWeekly=orderMapper.countOrderWeekly(year);
            for(int i=0;i<orderCountWeekly.size();i++){
                OrderCountWeekly orderCount = orderCountWeekly.get(i);
                String week = String.valueOf(orderCount.getOrderWeek());
                UserActivityResponse response =new UserActivityResponse(week,orderCount.getOrderCount());
                results.add(response);

            }
            return results;
        }
        else if(type.equals("monthly")){
            List<OrderCountMonthly> orderCountMonthlyList = orderMapper.countOrderMonthly(year);
            for(int i=0;i<orderCountMonthlyList.size();i++){
                OrderCountMonthly orderCount = orderCountMonthlyList.get(i);
                String month = String.valueOf(orderCount.getOrderMonth());
                UserActivityResponse response =new UserActivityResponse(month,orderCount.getOrderCount());
                results.add(response);

            }
            return results;

        }//不同时间段
        else{
            List<OrderCountHourly> orderCountHourlyList = orderMapper.countOrdersByHour(year);
            Map<String, Integer> orderCountsByPeriod = new HashMap<>();
            for(int i=0;i<orderCountHourlyList.size();i++){
                int hour = orderCountHourlyList.get(i).getOrderHour();
                int count =orderCountHourlyList.get(i).getOrderCount();
                String period = determinePeriod(hour); // 根据小时确定时间段
                orderCountsByPeriod.merge(period, count, Integer::sum);
            }//把哈希表转换成需要的response
            for (Map.Entry<String, Integer> entry : orderCountsByPeriod.entrySet()) {
                String period = entry.getKey();
                int orderCount = entry.getValue();
                results.add(new UserActivityResponse(period, orderCount));
            }
            return results;

//            for(int i=0;i<orderCountHourlyList.size();i++){
//                OrderCountHourly orderCount = orderCountHourlyList.get(i);
//                String period = determinePeriod(orderCount.getOrderHour());
//                UserActivityResponse response = new UserActivityResponse(period,orderCount.getOrderCount());
//
//            }
        }
        //return results;
    }

    private String determinePeriod(int hour) {
        if (hour >= 0 && hour < 6) return "00:00-05:59";
        if (hour >= 6 && hour < 11) return "06:00-10:59";
        if (hour >= 11 && hour < 13) return "11:00-12:59";
        if (hour >= 13 && hour < 18) return "13:00-17:59";
        if (hour >= 18 && hour < 20) return "18:00-19:59";
        return "20:00-23:59";
    }

    public List<UserFeatureResponse> getUserFeature(UserFeatureRequest request){
        List<UserFeatureResponse> results=new ArrayList<>();
        String type= request.getType();
        int merchantID= request.getMerchant();
        //  1. 商户用餐次数分析
        if(type.equals("merchant")){
            //      - 根据merchantID在order里获取下过单的userID
            //      - 根据userID在user表里获取相关信息
            //      - 根据merchantID和userID获取count
//            List<OrderEntity> orderEntities = orderMapper.selectOrderByMerchantID(request.getMerchant());

            List<Integer> userLists = orderMapper.selectDistinctUserbyMerchant(merchantID);
            for(int i=0;i<userLists.size();i++){
                UserFeatureResponse response =new UserFeatureResponse();
                int userID=userLists.get(i);
                UserEntity userEntity=userMapper.selectUserById(userID);
                response=setUserFeature(userEntity);
                response.setItem("商户用餐次数");
                Integer count = orderMapper.countByMerchant_idAndUser_id(merchantID,userID);
                if(count==null) count =0;
                response.setCount(count);
                results.add(response);
            }

            return results;

        }  //2. 评价数量分析
        else if(type.equals("reviewCount")){
            //在merchantReview中获取userList
            List<Integer> userLists=merchantReviewMapper.selectDistinctUser();
            for(int i=0;i<userLists.size();i++){
                UserFeatureResponse response =new UserFeatureResponse();
                int userID=userLists.get(i);
                UserEntity userEntity=userMapper.selectUserById(userID);
                response=setUserFeature(userEntity);
                response.setItem("评价数量");
                Integer count = merchantReviewMapper.countByUser_id(userID);
                if(count==null) count =0;
                response.setCount(count);
                results.add(response);
            }
            return results;



        }//  3. 评分分数分析       - 一个用户对所有商户的评价分数的平均值
        else {
            List<Integer> userLists=merchantReviewMapper.selectDistinctUser();
            for(int i=0;i<userLists.size();i++){
                UserFeatureResponse response =new UserFeatureResponse();
                int userID=userLists.get(i);
                UserEntity userEntity=userMapper.selectUserById(userID);
                response=setUserFeature(userEntity);
                response.setItem("评分分数");
                Float count = merchantReviewMapper.averageRatingByUserID(userID);
                //if(count==null) count =0.0;
                response.setCount(count);
                results.add(response);
            }
            return results;

        }
    }
    public String mapAgeToGroup(int age) {
        if (age < 0) {
            throw new IllegalArgumentException("Age cannot be negative.");
        }
        if (age <= 18) {
            return "0-18";
        } else if (age <= 25) {
            return "19-25";
        } else if (age <= 35) {
            return "26-35";
        } else if (age <= 45) {
            return "36-45";
        } else if (age <= 60) {
            return "46-60";
        } else {
            return "60+";
        }
    }

    public UserFeatureResponse setUserFeature(UserEntity userEntity){
        UserFeatureResponse response =new UserFeatureResponse();
        int gender=userEntity.getGender();
        if(gender==0){
            response.setGender("男");
        }
        else {
            response.setGender("女");
        }
        int role = userEntity.getRole();
        if(role==0){
            response.setRole("学生");
        }else {
            response.setRole("教职工");
        }
        String ageGroup=mapAgeToGroup(userEntity.getAge());
        response.setAge_group(ageGroup);
        return response;
    }


}
